<template>
  <div class="asset-file-upload-button">
    <div class="btn-row">
      <!-- 选择文件 -->
      <el-upload
        :multiple="multiple"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="onUploadChange"
        :before-upload="beforeUpload"
        :http-request="noop"
        :accept="accept"
        :disabled="isUploading"
      >
        <el-button type="primary" size="small" :loading="isUploading">
          <el-icon><UploadFilled /></el-icon>
          选择文件
        </el-button>
      </el-upload>

      <!-- 选择文件夹（同一行显示） -->
      <el-button
        v-if="directory"
        size="small"
        :disabled="isUploading"
        @click="pickDirectory"
      >
        <el-icon><FolderOpened /></el-icon>
        选择文件夹
      </el-button>

      <!-- 隐藏的目录选择 input -->
      <input
        ref="dirPickerRef"
        class="dir-input"
        type="file"
        webkitdirectory
        directory
        multiple
        @change="onDirectoryPicked"
      />

      <!-- 行内提示（可按需删除） -->
      <span class="inline-tip">
        支持图片、PDF、Office、ZIP；单个文件建议 &lt; {{ maxSizeMB }}MB
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
import { UploadFilled, FolderOpened } from '@element-plus/icons-vue'

const props = defineProps({
  uploadFn: { type: Function, required: true }, // uploadFn(FormData)
  accept:   { type: String,  default: '.png,.jpg,.jpeg,.webp,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar' },
  maxSizeMB:{ type: Number,  default: 100 },
  multiple: { type: Boolean, default: true },
  directory:{ type: Boolean, default: true },
})
const emit = defineEmits(['uploaded','error'])

const dirPickerRef = ref(null)
const pending = ref([])
const isUploading = ref(false)

const noop = () => {}

function beforeUpload(file) {
  const ok = file.size / 1024 / 1024 < props.maxSizeMB
  if (!ok) {
    getCurrentInstance()?.proxy?.$modal?.msgError?.(`文件 ${file.name} 超过 ${props.maxSizeMB}MB`)
    return false
  }
  return true
}

/** 选择文件 -> 立即上传 */
async function onUploadChange(_uploadFile, uploadFiles) {
  pending.value = (uploadFiles || []).map(f => ({
    raw: f.raw || f,
    relativePath: f.relativePath || f.raw?.webkitRelativePath || ''
  }))
  await uploadNow()
}

/** 选择文件夹 -> 立即上传 */
function pickDirectory() {
  dirPickerRef.value?.click()
}
async function onDirectoryPicked(e) {
  const files = Array.from(e.target.files || [])
  pending.value = files.map(raw => ({
    raw,
    relativePath: raw.webkitRelativePath || ''
  }))
  e.target.value = ''
  await uploadNow()
}

/** 真正上传 */
async function uploadNow() {
  if (!pending.value.length) return
  const fd = new FormData()
  let cnt = 0
  for (const f of pending.value) {
    if (!beforeUpload(f.raw)) continue
    fd.append('files', f.raw)
    fd.append('relativePaths', f.relativePath || '')
    cnt++
  }
  if (!cnt) return

  isUploading.value = true
  try {
    await props.uploadFn(fd)
    pending.value = []
    emit('uploaded', { count: cnt })
  } catch (e) {
    emit('error', e)
  } finally {
    isUploading.value = false
  }
}
</script>

<style scoped>
/* 一行并排 + 自动换行 */
.btn-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* 隐藏目录 input（不占位、可触发） */
.dir-input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
  pointer-events: none;
}

.inline-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}
</style>
